﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Common;
public class AssemblyRun : MonoBehaviour {

    public int AssemblyStatus; //安装状态: 1-布局 2-联线   
    public Text Notice;
    public List<GameObject> layoutComponents=new List<GameObject>(); // 安装元件列表
    public List<GameObject> wires = new List<GameObject>();//导线列表
    public List<GameObject> cables = new List<GameObject>();//电缆列表
    public GameObject[][] wiringObjects = new GameObject[45][];//布线元件列表
    public GameObject wiringPoints;
    public GameObject schematic;
    public  GameObject FlyLine;
    public GameObject ComponentList; //元件选择列表
    public GameObject ToggleHelp;   
    public AudioClip success;
    public AudioClip fail;
    public Button btnLayout;
    public Button btnWiring;
    /*布局相关参数*/
    public int layoutIndex; //元件布局顺序
    public int wiringIndex; //布线顺序
    public int componentIsFit; //元件布局是否已完成
    public Vector3 mainCameraTrans; //主摄像初始坐标
    public float mainCameraView;  //主摄像头
    /*布线相关参数*/
    public string StartPointName;
    public string EndPointName;
    public Vector3 StartFly;
    public int isFly;
    public int CurWire=-1;

    void Awake()
    {
        Init();
    }

    // Use this for initialization
    void Start () {
        //Init();
	}
	
	// Update is called once per frame
	void Update () {
		
	}
    //电路安装初始化
    public void Init()
    {
        GetObjects();
        GetWires();
        GetCables();
        GetWiringObjects();
      
        //元件选择列表
        ComponentList = GameObject.Find("ComponentList");
        ComponentList.SetActive(false);
        //隐藏原理图
        schematic = GameObject.Find("Schmatic");
        schematic.SetActive(false);
        //获得飞线
        FlyLine = GameObject.Find("FlyLine");
        FlyLine.SetActive(false);
        //原理图红线不显示
        for (int i = 0; i < wiringObjects.Length; i++)
        {
            if (wiringObjects[i][0].GetComponent<CanvasGroup>() == false)
            {
                wiringObjects[i][0].AddComponent<CanvasGroup>();                
            }
            wiringObjects[i][0].GetComponent<CanvasGroup>().alpha = 0;
        }
        //布线点设置不显示
        wiringPoints = GameObject.Find("WiringPoints");
        wiringPoints.SetActive(false);
        //操作提示面板
        Notice = GameObject.Find("Notice").GetComponent<Text>();
        Notice.text = "请点击按钮，进入元件安装或导线连接操作练习。";
        //隐藏元件位置提示开关
        ToggleHelp = GameObject.Find("ToggleHelp");
        ToggleHelp.SetActive(false);
        //添加声音
        success = Resources.Load("Audio/success", typeof(AudioClip)) as AudioClip;
        fail = Resources.Load("Audio/fail", typeof(AudioClip)) as AudioClip;
        //获取相机初始位置
        mainCameraTrans = Camera.main.transform.position;
        mainCameraView = Camera.main.fieldOfView;
    }
    
    //初始化布局元件列表
    void GetObjects()
    {
        foreach(string name in Global.layout_component_name)
        {
            GameObject tmp=GameObject.Find(name);
            if (tmp)
            {
                layoutComponents.Add(tmp);
            }
        }
    }
    //初始化电路导线
    void GetWires()
    {
        foreach(string name in Global.wires_name)
        {
            GameObject tmp = GameObject.Find(name);
            if (tmp)
            {
                wires.Add(tmp);
            }
        }
    }

    //初始化电缆
    void GetCables()
    {
        foreach(string name in Global.cables_name)
        {
            GameObject tmp = GameObject.Find(name);
            if (tmp)
            {
                cables.Add(tmp);
            }
        }
    }

    void GetWiringObjects()
    {
        for(int i=0;i<Global.WiringObjectsName.Length;i++)
        {
            wiringObjects[i] = new GameObject[4];
            for (int j=0;j<4;j++)
            {              
                wiringObjects[i][j] = GameObject.Find(Global.WiringObjectsName[i][j]);
                
            }
        }

    }

    //点击按钮进入组装元件状态
    public void BtnAssemble(){
         if (ComponentIsFit())
        {
            return;
        }
        AssemblyStatus = 1;
        AssembleInit(); 
    }
    
    //点击按钮进入布线状态
    public void BtnWiring()
    {
        if (ComponentIsFit())
        {
            return;
        }
        AssemblyStatus = 2;
       WiringInit();
    }



    //组装初始化
    void AssembleInit() {
        layoutIndex = 0;
        wiringIndex = 0;
        componentIsFit = 0;
        Toggle toggle = ToggleHelp.GetComponent<Toggle>();
        toggle.isOn = false;
        HideComponent(layoutComponents);
        HideComponent(wires);
        HideComponent(cables);
        //隐藏原理图
        schematic.SetActive(false);
    
        for (int i = 0; i < wiringObjects.Length; i++)
        {
            //原理图红线不显示，去掉闪烁
            if (wiringObjects[i][0].GetComponent<CanvasGroup>() == false)
            {
                wiringObjects[i][0].AddComponent<CanvasGroup>();                
            }
            wiringObjects[i][0].GetComponent<CanvasGroup>().alpha = 0;
        }
        //布线点设置不显示
        wiringPoints.SetActive(false);
        //显示元件列表
        ComponentList.SetActive(true);
        //显示帮助
        ToggleHelp.SetActive(true);
        //设置公告
        Notice.text = "请点击选择元件列表中的元件，拖动到正确的位置,单击鼠标右键进行安装元件。";
        Camera.main.transform.position = mainCameraTrans;
        Camera.main.fieldOfView = mainCameraView;
    }

    //布线初始化
    void WiringInit(){
        layoutIndex = 0;
        wiringIndex = 0;
        ShowComponent(layoutComponents);
        HideComponent(wires);
        HideComponent(cables);
        ComponentList.SetActive(false);
        schematic.SetActive(true);
        wiringPoints.SetActive(true);
        
        for (int i = 0; i < wiringObjects.Length; i++)
        {
            //原理图红线不显示
            if (wiringObjects[i][0].GetComponent<CanvasGroup>() == false)
            {
                wiringObjects[i][0].AddComponent<CanvasGroup>();
            }
            wiringObjects[i][0].GetComponent<CanvasGroup>().alpha = 0;

            if (wiringObjects[i][0].GetComponent<UITwinking>()&&i>0) {
                Destroy(wiringObjects[i][0].GetComponent<UITwinking>());
                Destroy(wiringObjects[i][0].GetComponent<WiringHelp>());
            }
               
            //添加布线点提示脚本
            if (wiringObjects[i][2].GetComponent<WiringPoints>() == null)
            {
                wiringObjects[i][2].AddComponent<WiringPoints>();
            }
            if (wiringObjects[i][3].GetComponent<WiringPoints>() == null)
            {
                wiringObjects[i][3].AddComponent<WiringPoints>();
            }
        }

        //显示帮助
        ToggleHelp.SetActive(false);
        //设置公告
        Notice.text = "请根据原理图提示，点击正确的接线端子连接线路。";
        //设置相机
        Camera.main.transform.position = new Vector3(-0.1f,0.45f,0);
        Camera.main.fieldOfView = 23;
        

    }


    //隐藏元件系列
    void HideComponent(List<GameObject> Component)
    {
        foreach (GameObject Object in Component)
        {
            if (Object)
            {
                Object.SetActive(false);
            }
        }
    }

    //显示元件
    void ShowComponent(List<GameObject> Component)
    {
        foreach (GameObject Object in Component)
        {
            if (Object)
            {
                Object.SetActive(true);
            }
        }
    }

    /*元件安装相关操作*/
    //点击线槽按钮
    /*元件布局安装相关操作*/
    //点击线槽
    public void BtnXianCao()
    {
        //当前元件是否安装完成，是继续选择元件，否元件无法选择
        if (ComponentIsFit())
        {
            return;
        }
        FixComponent(0, 4);

    }

    //点击导轨
    public void BtnDaoGui()
    {
        //当前元件是否安装完成，是继续选择元件，否元件无法选择
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(5, 7);

    }

    //点击QF
    public void BtnQF()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(8, 8);
    }

    //点击Fuse1
    public void BtnFuse1()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(9, 10);
    }

 

    //点击FR
    public void BtnFR()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(11, 11);
    }

    //点击KM
    public void BtnKM()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(12, 13);
    }

    //点击XT
    public void BtnXT()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(14, 21);
    }

    //点击LED绿
    public void BtnLedGreen()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(22, 23);
    }


    //点击LED红
    public void BtnLedRed()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(24, 24);
    }

    //点击S1
    public void BtnSGreen()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(25, 26);
    }

    //点击S2
    public void BtnSRed()
    {
        if (ComponentIsFit())
        {
            return;
        }

        FixComponent(27, 27);
    }

    //选择安装元件
    void FixComponent(int minIndex, int maxIndex)
    {
        if (layoutIndex >= layoutComponents.Count)
        {
            MessageBox.Show("提示", "你已经完成全部安装！", "去接线", "取消");
            MessageBox.confim = () => {
                //这里写你自己点击确定按钮后的操作
               // GameObject.Find("AnZhuang_script").GetComponent<AnZhuang>().BtnWiring();
                Debug.Log("");
            };
            MessageBox.cancel = () => {
                //这里写你自己点击确定按钮后的操作
                Debug.Log("do nothing");
            };
            return;
        }


        if (layoutIndex >= minIndex && layoutIndex <= maxIndex)
        {
            DragComponent(layoutComponents[layoutIndex]);
            AudioSource.PlayClipAtPoint(success, Vector3.zero);
            Notice.text = "太棒了，选择正确，去安装元件吧，加油呀！";
        }
        else
        {
            AudioSource.PlayClipAtPoint(fail, Vector3.zero);
            Notice.text = "元件错误，请选择正确的安装元件，再试试吧！";
        }

    }


    //鼠标选择元件并拖动
    void DragComponent(GameObject obj)
    {
        obj.SetActive(true);
        //在原点位置实例化要放置的一个元件
        GameObject obj_temp = GameObject.Instantiate(obj, new Vector3(0, 0, 0), obj.transform.rotation, GameObject.Find("zfz200818").transform);
        obj_temp.AddComponent<FollowMouse>();
        obj_temp.GetComponent<FollowMouse>().targetTransform = obj.transform;
    }

    //检测元件当前的安装状态
    bool ComponentIsFit()
    {
        //是否正在安装元件
        if (componentIsFit == 1)
        {
            MessageBox.Show("提示", "　 当前元件安装未完成！");
            MessageBox.confim = () =>
            {
                //这里写你自己点击确定按钮后的操作
                Debug.Log("");
            };
            return true;
        }
        else
        {
            // 设置正在安装元件状态           
            return false;
        }
    }

    /*安装位置提示开关*/
    public void isHelp()
    {
        Toggle toggle = ToggleHelp.GetComponent<Toggle>();
        if (layoutIndex < layoutComponents.Count)
        {
            if (toggle.isOn)
            {
                //设置目标元件半透明 
                layoutComponents[layoutIndex].SetActive(true);
                string shader = "Legacy Shaders/Transparent/Diffuse";
                SetRender(layoutComponents[layoutIndex].transform, shader, 0.5f);
               // Debug.Log("ison");
            }
            else if (!toggle.isOn)
            {
                layoutComponents[layoutIndex].SetActive(true);
                string shader = "Legacy Shaders/Transparent/Diffuse";
                SetRender(layoutComponents[layoutIndex].transform, shader, 0f);
               // Debug.Log("isoff");
            }
        }


    }

    public void BtnHelp()
    {

        //弹出考场说明
        string AssemblyDescription;
        AssemblyDescription = "1.线路安装分为器件安装和线路连接两部分操作，单击相应按钮即可进操作。\n" +
                          "2.按住W,S,A,D键，可上、下、左、右移动视角位置，拨动鼠标滚轮缩放视野。\n" +
                         "3.器件安装时，鼠标左键单击元件列表选取元件，拖动鼠标到安装位置后，单击右键确定放置元件。\n" +
                         "4.连接导线时，请根据原理图提示的导线顺序连线；鼠标左键单击要连接的端子连线，单击鼠标右键可取消连线。\n";
        NoticeBox.Show("线路安装操作说明", AssemblyDescription, "确定");
        NoticeBox.confim = () =>
        {
            return;
            //BtnAssemble();
            // BtnWiring();
        };
    }


    void SetRender(Transform targetTransform, string shader, float num)
    {
        foreach (Transform child in targetTransform.gameObject.GetComponentsInChildren<Transform>(true))
        {
            Renderer renderer = child.GetComponent<Renderer>();
            if (renderer)
            {
                for (int i = 0; i < renderer.materials.Length; i++)
                {
                    renderer.materials[i].shader = Shader.Find(shader);
                    renderer.materials[i].color = new Color(
                    renderer.materials[i].color.r,
                    renderer.materials[i].color.g,
                    renderer.materials[i].color.b,
                    num);
                }

            }
        }
    }

}
